package thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//编写代码, 实现线程池案例
class MyThreadPool {
    // 用来存放线程池中 要执行的任务
     BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(50);

     public MyThreadPool(int n) {
         for (int i = 0; i < n; i++) {
             Thread t = new Thread(() -> {
                while (true) {
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
             });
             t.start();
         }
     }

     // 向线程池中添加任务
     public void submit(Runnable runnable) throws InterruptedException {
         queue.put(runnable);
     }

}

public class demo14 {

    public static void main(String[] args) throws InterruptedException {
//        ExecutorService service = Executors.newFixedThreadPool(6);
        MyThreadPool myThreadPool = new MyThreadPool(5);
        for(int i = 0; i < 1000; i++) {
           int id = i;
           myThreadPool.submit(new Runnable() {
               @Override
               public void run() {
                   System.out.println("i = " + id);
               }
           });
       }

    }
}
